package com.example.simpletask

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.core.graphics.createBitmap
import java.io.BufferedInputStream
import java.io.BufferedWriter
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter

class DbHelper(val context: Context)
    : SQLiteOpenHelper(context, "MissionData.db", null, 2) {

    override fun onCreate(db: SQLiteDatabase) {
        val createMissionTabSQL = "create table if not exists missions(" +
                "missionid integer unique primary key," +
                "content text," +
                "steps integer," +
                "stage integer," +
                "attrs integer)"

        val createPicTabSQL = "create table if not exists pictures(" +
                "parentid integer," +
                "path text)"

        db.execSQL(createMissionTabSQL)
        db.execSQL(createPicTabSQL)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("drop table if exists missions")
        db.execSQL("drop table if exists pictures")
        onCreate(db)
    }

    fun insertMission(id: Int, content: String, steps: Int, attrs: Int = 0): Long {
        val db = this.writableDatabase
        val values = ContentValues().apply {
            put("missionid", id)
            put("content", content)
            put("steps", steps)
            put("attrs", attrs)
        }
        Log.d("TAG", "insertMission" + id.toString())
        return db.insert("missions", null, values)
    }

    fun deleteMission(id: Int): Int {
        val db = this.readableDatabase
        return db.delete("missions", "missionid = ?", arrayOf(id.toString()))
    }

    fun updateMission(id: Int, content: String, steps: Int, stage: Int, attrs: Int): Int {
        val db = this.writableDatabase
        val values = ContentValues().apply {
            put("content", content)
            put("steps", steps)
            put("stage", stage)
            put("attrs", attrs)
        }

        return db.update("missions", values, "missionid = ?", arrayOf(id.toString()))
    }

//    因为左右滑动卡片更改步骤很常见，所以这个更新独立出来，减少计算压力
    fun updateStage(id: Int, stage: Int): Int {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put("stage", stage)
        return db.update("missions", values, "missionid = ?", arrayOf(id.toString()))
    }

    @SuppressLint("Range")
    fun loadAllMissions(): ArrayList<Mission> {
        val db = this.readableDatabase
        val cursor = db.query("missions", null, null,
            null, null, null, null)
        val list = ArrayList<Mission>()
        if (cursor.moveToFirst()) {
            do {
                val id = cursor.getInt(cursor.getColumnIndex("missionid"))
                val content = cursor.getString(cursor.getColumnIndex("content"))
                val steps = cursor.getInt(cursor.getColumnIndex("steps"))
                val stage = cursor.getInt(cursor.getColumnIndex("stage"))
                Log.d("TAG", "loadAllMissions: $id, $content, $steps, $stage")
                list.add(Mission(id, content, steps, stage))
            } while (cursor.moveToNext())
        }
        return list
    }

    /**
     * 添加图片到数据库
     * 但是要保证一个任务（即parentid）只有最多一张图片与之对应
     * 若已有图了，就转为updatePic
     */
    fun addPic(parentid: Int, path: String): Long {
        // 如果找到了
        if (findPic(parentid)) {
            Log.d("TAG", "updatePic: ")
            return updatePic(parentid, path) as Long
        }
        // 没找到
        val db = this.writableDatabase
        val values = ContentValues().apply {
            put("parentid", parentid)
            put("path", path)
        }
        Log.d("TAG", "addPic: ")
        return db.insert("pictures", null, values)
    }

    /**
     * 删除某张图片
     */
    fun deletePic(parentid: Int): Int {
        val db = this.writableDatabase
        return db.delete("pictures", "parentid = ?", arrayOf(parentid.toString()))
    }

    /**
     * 主要是负责判断有没有图片
     */
    fun findPic(parentid: Int): Boolean {
        val db = this.readableDatabase
        val cursor = db.query("pictures", null, "parentid = ?",
            arrayOf(parentid.toString()), null, null, null)
        return cursor.moveToFirst() // 这个很好地符合要求
    }

    /**
     * 找到图片的路径并返回
     */
    fun findPicPath(parentid: Int): String {
        var path = ""
        return path
    }

    /**
     * 更新图片路径
     */
    fun updatePic(parentid: Int, path: String): Int {
        return 0
    }
}



